// pages/cart/index.js
import { getSetting, openSetting, chooseAddress, showModal, showToast} from '../../utils/asyncWx'

Page({
  data: {
    address: {},
    cart: [],
    allChecked: false,
    totalPrice: 0,
    totalNum: 0
  },

  onShow () {
    const address = wx.getStorageSync('address');
    const cart = wx.getStorageSync('cart');
    this.setData({address})
    this.setCart(cart)
  },

  /* 选择收货地址 */
  async handleChooseAddress () {
    try {
      const settings = await getSetting()
      const scopeAddress = settings.authSetting['scope.address']
      if (scopeAddress === false) await openSetting()
      const address = await chooseAddress()
      address.all = address.provinceName + address.cityName + address.countyName + address.detailInfo
      wx.setStorageSync('address', address)
    } catch (error) {
      console.log(error); 
    }
  },

  /* 单选改变 */
  handleItemCheckedChange(e) {
    const goods_id = e.currentTarget.dataset.id
    let {cart} = this.data
    let index = cart.findIndex(v=>v.goods_id === goods_id)
    cart[index].checked = !cart[index].checked
    this.setCart(cart)
  },

  /* 全选中改变 */
  handleAllCheckedChange() {
    let {cart, allChecked} = this.data
    allChecked = !allChecked
    cart.forEach(value => {
      value.checked = allChecked
    })
    this.setCart(cart)
  },

  /* 商品数量改变 */
  async handleNumChange(e) {
    const {id, opration} = e.currentTarget.dataset
    let {cart} = this.data
    let index = cart.findIndex(v => v.goods_id === id)
    if (cart[index].num === 1 && opration === -1) {
      const res = await showModal({content: '确定删除该商品？'})
      if (res.confirm) {
        cart.splice(index,1)
        this.setCart(cart)
      }
    } else {
      cart[index].num += opration
      this.setCart(cart)
    }
  },

  /* 结算 */
  async handleSettlement() {
    let {address,cart} = this.data
    if (!address.userName) {
      await showToast({title: '请选择收获地址'})
      return
    }
    if (cart.length===0) {
      await showToast({title:'请选择商品'})
      return
    }
    wx.navigateTo({url: '/pages/pay/index'})
  },

  /* 设置cart */
  setCart(cart) {
    let allChecked = true
    let totalPrice = 0
    let totalNum = 0
    cart.forEach(v => {
      if (v.checked) {
        totalPrice += v.num * v.goods_price
        totalNum += v.num
      } else {
        allChecked = false
      }
    });
    allChecked = cart.length !== 0 ? allChecked : false
    this.setData({
      cart,
      allChecked,
      totalPrice,
      totalNum
    })
    wx.setStorageSync('cart',cart)
  },
})